/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.web;

import java.text.NumberFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.ap.entity.Advance;
import com.jeeplus.modules.ap.entity.Recel;
import com.jeeplus.modules.ap.service.AdvanceService;
import com.jeeplus.modules.ap.service.RecelService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.entity.TmsWaybill;
import com.jeeplus.modules.tms.service.TmsWaybillService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.fee.entity.Cope;
import com.jeeplus.modules.fee.service.CopeService;

/**
 * 应付Controller
 * @author 李超辉
 * @version 2018-02-01
 */
@Controller
@RequestMapping(value = "${adminPath}/fee/cope")
public class CopeController extends BaseController {

	@Autowired
	private CopeService copeService;
	@Autowired
	private TmsWaybillService tmsWaybillService;
	@Autowired
	private AdvanceService advanceService;
	@Autowired
	private RecelService recelService;
	
	@ModelAttribute
	public Cope get(@RequestParam(required=false) String id) {
		Cope entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = copeService.get(id);
		}
		if (entity == null){
			entity = new Cope();
		}
		return entity;
	}
	
	/**
	 * 应付列表页面
	 */
	@RequiresPermissions("fee:cope:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fee/copeList";
	}
	
		/**
	 * 应付列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fee:cope:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Cope cope, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			cope.setProject(pro);
		}
		Page<Cope> page = copeService.findPage(new Page<Cope>(request, response), cope);
		List<Cope>copes=page.getList();
		NumberFormat nf = NumberFormat.getInstance();
		for(Cope r:copes){
			TmsWaybill t=new TmsWaybill();
			t.setPid(r.getPid());
			List<TmsWaybill> bills=tmsWaybillService.findList(t);
			double yskp=0.0;
			for(TmsWaybill bill:bills){
				Advance a=advanceService.findUniqueByProperty("bill",bill.getId());
				if(a!=null){
					yskp+=Double.parseDouble( a.getSfzje());
				}
				Recel cel=recelService.findUniqueByProperty("bill",bill.getId());
				if(cel!=null){
					yskp+=Double.parseDouble( cel.getSfzje());
				}
			}
          r.setYf(nf.format(yskp).replaceAll(",",""));
			r.setWf(nf.format(Double.parseDouble(r.getFreight())-yskp).replaceAll(",",""));

		}
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑应付表单页面
	 */
	@RequiresPermissions(value={"fee:cope:view","fee:cope:add","fee:cope:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Cope cope, Model model) {
		model.addAttribute("cope", cope);
		return "modules/fee/copeForm";
	}

	/**
	 * 保存应付
	 */
	@ResponseBody
	@RequiresPermissions(value={"fee:cope:add","fee:cope:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Cope cope, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, cope)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		//新增或编辑表单保存
		copeService.save(cope);//保存
		j.setSuccess(true);
		j.setMsg("保存应付成功");
		return j;
	}
	
	/**
	 * 删除应付
	 */
	@ResponseBody
	@RequiresPermissions("fee:cope:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Cope cope, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		copeService.delete(cope);
		j.setMsg("删除应付成功");
		return j;
	}
	
	/**
	 * 批量删除应付
	 */
	@ResponseBody
	@RequiresPermissions("fee:cope:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			copeService.delete(copeService.get(id));
		}
		j.setMsg("删除应付成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fee:cope:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Cope cope, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "应付"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Cope> page = copeService.findPage(new Page<Cope>(request, response, -1), cope);
    		new ExportExcel("应付", Cope.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出应付记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
    
    @ResponseBody
    @RequestMapping(value = "detail")
	public Cope detail(String id) {
		return copeService.get(id);
	}
	

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fee:cope:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Cope> list = ei.getDataList(Cope.class);
			for (Cope cope : list){
				try{
					copeService.save(cope);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条应付记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条应付记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入应付失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/cope/?repage";
    }
	
	/**
	 * 下载导入应付数据模板
	 */
	@RequiresPermissions("fee:cope:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "应付数据导入模板.xlsx";
    		List<Cope> list = Lists.newArrayList(); 
    		new ExportExcel("应付数据", Cope.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/cope/?repage";
    }
	

}